package com.wuliupai.delivery.wuliupaidelivery.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.RemoteViews;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.utils.ActivityCollector;
import com.wuliupai.delivery.wuliupaidelivery.utils.FileUtils_;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 后台下载
 */
public class DownloadService extends IntentService {

    private FileUtils_ myUtil;

    //更新文件路径
    private final String APK_PATH = "update/";
    private final String APK_NAME = "paigekuaiyun.apk";

    //保单文件路径
    private final String POLICY_PATH = "policy/";
    private String POLICY_NAME = "policy%s.pdf";

    private NotificationManager notificationMrg;

    private Map<String, Notification> notificationCache = new HashMap<String, Notification>();
    private Holder holder;
    private int flag = 0;

    private LocalBroadcastManager lbm;
    private boolean isSendBroadcast;//是否发送广播

    /**
     * downloadType下载文件的类型
     * 1:更新,下载apk包
     * 2:下载保单
     */
    private int downloadType;
    private File downloadFilePath = null;//文件存在为位置
    private String url = "";//下载的地址
    private String policyName;

    public DownloadService() {
        super("DownloadService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        lbm = LocalBroadcastManager.getInstance(this);
        notificationMrg = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        myUtil = FileUtils_.getInstance_(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    // 状态栏视图更新
    private Notification displayNotificationMessage(Notification notification, int count, int flag, String url) {
        RemoteViews contentView1 = notification.contentView;
        contentView1.setTextViewText(R.id.n_title, "正在下载“派哥同城”");
        contentView1.setTextViewText(R.id.n_text, count + "% ");
        contentView1.setProgressBar(R.id.n_progress, 100, count, false);
        notification.contentView = contentView1;
        // 提交一个通知在状态栏中显示。如果拥有相同标签和相同id的通知已经被提交而且没有被移除，该方法会用更新的信息来替换之前的通知。
        notificationMrg.notify(flag, notification);
        return notification;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            downloadType = intent.getIntExtra("downloadType", 0);
            isSendBroadcast = intent.getBooleanExtra("isSendBroadcast", true);
            switch (downloadType) {
                case 1://1:更新,下载apk包
                    downloadFilePath = new File(myUtil.creatFolderAndReturnPath(APK_PATH), APK_NAME);

                    url = intent.getStringExtra("downloadUrl");
//                    url = "http://apk.lenovomm.com/201612161650/21986e713254c3a517eea01f52ce598d/dlserver/fileman/s3/apk/app/app-apk-lestore/4495-2016-11-30043021-1480494621827.apk?v=5&clientid=15808-1a2-2-9999-1-3-1_240_iamp5UIDecd5a4bfda197cddde379af7ct19700101823038993_c303d1p30&pn=com.UCMobile";
                    break;
                case 2://2:下载保单
                    String orderCode = intent.getStringExtra("arg1");
                    policyName = String.format(POLICY_NAME, orderCode);
                    downloadFilePath = new File(myUtil.creatFolderAndReturnPath(POLICY_PATH), policyName);
                    url = intent.getStringExtra("url");
//                WuliupaiApplication.toast("保单下载中");
                    break;
            }
            Runnable start = () -> loadFile(url, ++flag);

            new Thread(start) {
            }.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    double m = 0.0;

    public void loadFile(String url, int flag) {
//        String TAG = "wlp";
        Intent notificationIntent = new Intent(getApplicationContext(), this.getClass());
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        // addflag设置跳转类型
        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
        // 创建Notifcation对象，设置图标，提示文字
        long number = 100;
        Notification notification = new Notification(R.mipmap.ic_launcher, "下载更新", number);// 设定Notification出现时的声音，一般不建议自定义
        // System.currentTimeMillis()
        notification.flags |= Notification.FLAG_ONGOING_EVENT;// 出现在 “正在运行的”栏目下面
        RemoteViews contentView1 = new RemoteViews(getPackageName(), R.layout.notification_version);
        contentView1.setTextViewText(R.id.n_title, "准备下载");
        contentView1.setTextViewText(R.id.n_text, "当前进度：" + 0 + "% ");
        contentView1.setProgressBar(R.id.n_progress, 100, 0, false);
        notification.contentView = contentView1;
        notification.contentIntent = contentIntent;


        final Request request = new Request.Builder().url(url).build();
        final Call call = new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    long length = response.body().contentLength();
                    long current = 0;
                    is = response.body().byteStream();
                    fos = new FileOutputStream(downloadFilePath);
                    float count = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        count += len;
                        // 从字节数组读取数据read(buf)后，返回，读取的个数，count中保存，已下载的数据字节数
                        double temp = count / length;
                        if (temp >= m) {
                            //每下载1%更新一下通知
                            m += 0.01;
                            // m += 0.1;//每下载10%更新一下通知
                            int load = (int) (count * 100 / length);

                            if (isSendBroadcast) {
                                Intent intent = new Intent();
                                intent.setAction(BroadcastChannels.Channel_DownloadApk);
                                intent.putExtra("progress", load);
                                lbm.sendBroadcast(intent);
                            }

                            sendMsg(1, load, url, notification, flag, null);
                        }
                        // 函数调用handler发送信息
                    }
                    fos.flush();

                    // 文件输出流为空，则表示下载完成，安装apk文件
                    Uri Url = Uri.fromFile(downloadFilePath);
                    sendMsg(2, 0, url, notification, 0, Url);

                    is.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != is) {
                            is.close();
                        }
                        if (null != fos) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

//    private AlertDialog mDialog;

//    private void showDialog() {
//
//        mDialog = new AlertDialog.Builder(this).create();
//        mDialog.setCanceledOnTouchOutside(false);//失去焦点不会消失
//        mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);//设定为系统级警告，关键
//        mDialog.show();
//        Window window = mDialog.getWindow();
//        window.setContentView(R.layout.dialog_download_service);
//
//        TextView tvTitle = (TextView) window.findViewById(R.id.tv_tipsTitle);
//        tvTitle.setText("物流派");
//
//        TextView tvContent1 = (TextView) window.findViewById(R.id.tv_tipsContent1);
//        TextView tvContent2 = (TextView) window.findViewById(R.id.tv_tipsContent2);
//
//        TextView tv_okBtn = (TextView) window.findViewById(R.id.tv_leftBnt);
//        tv_okBtn.setText("确定");
//        tv_okBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mDialog.dismiss();
//            }
//        });
//        tvContent1.setText("保单下载成功!");
//        tvContent2.setText("文件存储位置: SD卡" + MyUtil.APP_FILE_PATH + "/" + POLICY_PATH + policyName);
//    }

    private void sendMsg(int what, int c, String url, Notification notification, int flag, Uri uri) {
        Message msg = new Message();
        msg.what = what;// 用来识别发送消息的类型
        msg.arg1 = 0;
        holder = new Holder();
        holder.count = c;
        holder.url = url;
        holder.flag = flag;
        holder.notify = notification;
        holder.Uri = uri;
        msg.obj = holder;// 消息传递的自定义对象信息
        handler.sendMessage(msg);
    }

    // 定义一个Handler，用于处理下载线程与主线程间通讯
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            final Holder data = (Holder) msg.obj;
            if (!Thread.currentThread().isInterrupted()) {
                // 判断下载线程是否中断
                switch (msg.what) {
                    case 1:
                        if (data.count >= 99) {
                            notificationMrg.cancel(data.flag);
                            break;
                        }
                        Notification notification;
                        if (notificationCache.containsKey(data.url)) {
                            // 每次更新时，先以key，扫描hashmap，存在则读取出来。
                            notification = notificationCache.get(data.url);
                            notification = displayNotificationMessage(notification, data.count, data.flag, data.url);
                            notificationCache.put(data.url, notification);
                        } else {
                            // //第一次更新时，传入notification对象每次，将notification对象存入hashmap中
                            notification = data.notify;
                            notification = displayNotificationMessage(notification, data.count, data.flag, data.url);
                            notificationCache.put(data.url, notification);
                        }
                        break;
                    case 2:// 下载成功
                        if (1 == downloadType) {
                            openFile(data.Uri);
                        } else if (2 == downloadType) {
//                            showDialog();
                        }
                        break;
                    case -1:
//                        WuliupaiApplication.toast(msg.getData().getString("error"));
                        App.toast("下载失败~~");
                        break;
                    // 否则输出错误提示
                }
            }
            super.handleMessage(msg);
        }
    };

    public void openFile(Uri url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(url, "application/vnd.android.package-archive");
        startActivity(intent);
        if (isSendBroadcast) {
            // 退出 所有Activity
            ActivityCollector.finishAll();
            // 杀死该应用进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }
    }

    public class Holder {
        Notification notify;
        String url;
        int count;
        int flag;
        android.net.Uri Uri;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
